package by.yakusekmaxim.bookgid.webapp.page.admin.image;

import java.util.List;

import javax.inject.Inject;

import org.apache.wicket.AttributeModifier;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxLink;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;

import by.yakusekmaxim.bookgid.datamodel.Image;
import by.yakusekmaxim.bookgid.services.ImageService;
import by.yakusekmaxim.bookgid.util.ImageInterface;

public class InsertImagePanel extends Panel {

	@Inject
	private ImageService imageService;

	public InsertImagePanel(String id, final Label imageLabel, final ImageInterface author) {
		super(id);

		final InsertImagePanel panel = this;

		final List<Image> allImage = imageService.getAll();

		add(new ListView<Image>("list", allImage) {
			@Override
			protected void populateItem(ListItem<Image> item) {
				final Image image = item.getModelObject();
				AjaxLink<Void> ajaxInsertImage = new AjaxLink<Void>("ajaxInsertImage") {
					@Override
					public void onClick(AjaxRequestTarget target) {
						panel.add(AttributeModifier.replace("style",
								"display: none;"));
						target.add(panel);
						imageLabel.add(AttributeModifier.replace("src", image.getUrl()));
						imageLabel
						.add(AttributeModifier.replace("style", "display: block;"));
						target.add(imageLabel);
						author.setImage(image);
					}

				};

				Label imageLabel = new Label("image", "");
				imageLabel
						.add(AttributeModifier.replace("src", image.getUrl()));
				imageLabel
						.add(AttributeModifier.replace("alt", image.getName()));
				imageLabel.add(AttributeModifier.replace("title",
						image.getName()));
				ajaxInsertImage.add(imageLabel);
				item.add(ajaxInsertImage);

			}
		});

	}
}
